package com.leagsoft.emm.demo;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huawei.secoclient.sslvpn.ConstValue;
import com.huawei.secoclient.sslvpn.VpnUtils;
import com.huawei.secoclient.sslvpn.callback.OnConnectCallBack;
import com.huawei.secoclient.sslvpn.entity.ConnectEntity;
import com.huawei.secoclient.sslvpn.entity.ServerAddrEntity;
import com.leagsoft.emm.demo.util.ContentUriUtil;
import com.leagsoft.emm.demo.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 主页界面，处理连接，进入登录，修改密码，断开连接等接口
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "vpn-demo";
    private static final int GM_ENC = 1000;
    private static final int GM_SIG = 1001;

    private Button buConect, buTunnelMold, buDisconect;
    private EditText etConnectIp, etConnectPort;
    private CheckBox cbxRoutecover, cbxTcpBuffer, cbxAlgorithm;
    private LinearLayout llGmShow;
    private TextView tvGmEnc, tvGmSig;
    private int tunnelType = 2;
    private AlertDialog alertDialog; //单选框

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 1000);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 先判断有没有权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
            }
        }

        boolean flag = VpnUtils.initLog(this, getExternalFilesDir("VpnLog").getAbsolutePath(), ConstValue.LOG_TYPE_INFO);
        if (flag) {
            ToastUtil.show(MainActivity.this, "日志初始化成功");
        } else {
            ToastUtil.show(MainActivity.this, "日志初始化失败");
        }
        buDisconect = findViewById(R.id.bu_disconect);
        buConect = findViewById(R.id.bu_conect);
        buTunnelMold = findViewById(R.id.bu_tunnel_mold);
        cbxRoutecover = findViewById(R.id.cbx_routecover);
        cbxTcpBuffer = findViewById(R.id.cbx_tcp_buffer);
        cbxAlgorithm = findViewById(R.id.cbx_algorithm);
        llGmShow = findViewById(R.id.ll_gm_show);
        tvGmEnc = findViewById(R.id.tv_gm_enc);
        tvGmSig = findViewById(R.id.tv_gm_sig);
        etConnectIp = findViewById(R.id.et_connect_ip);
        etConnectPort = findViewById(R.id.et_connect_port);

        etConnectIp.setText("222.78.53.122");
        etConnectPort.setText("4431");

        buConect.setOnClickListener(this);
        buTunnelMold.setOnClickListener(this);
        tvGmEnc.setOnClickListener(this);
        tvGmSig.setOnClickListener(this);
        buDisconect.setOnClickListener(this);
        findViewById(R.id.bu_modify_password).setOnClickListener(this);
        findViewById(R.id.bu_log_path).setOnClickListener(this);
        findViewById(R.id.bu_vpn_status).setOnClickListener(this);


        cbxAlgorithm.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    llGmShow.setVisibility(View.VISIBLE);
                } else {
                    llGmShow.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bu_conect:
                goConnect();
                break;
            case R.id.bu_disconect:
                if (!VpnUtils.logout()) {
                    ToastUtil.show(MainActivity.this, "断开连接失败");
                }
                break;
            case R.id.bu_tunnel_mold:
                showSingleAlertDialog();
                break;
            case R.id.tv_gm_enc:
                chooseFile(GM_ENC);
                break;
            case R.id.tv_gm_sig:
                chooseFile(GM_SIG);
                break;
            case R.id.bu_modify_password:
                startActivity(new Intent(MainActivity.this, ModifyPasswordActivity.class));
                break;
            case R.id.bu_log_path:
                ToastUtil.show(MainActivity.this, VpnUtils.getLogPath());
                break;
            case R.id.bu_vpn_status:
                if (VpnUtils.getConnectStatus() == ConstValue.VPN_STATUS_CONNECTED) {
                    ToastUtil.show(MainActivity.this, "已连接");
                } else if (VpnUtils.getConnectStatus() == ConstValue.VPN_STATUS_DISCONNECT) {
                    ToastUtil.show(MainActivity.this, "未连接");
                }
                break;
        }
    }

    /**
     * 开始去连接
     */
    private void goConnect() {
        try {
            String serverAddress = etConnectIp.getText().toString();
            int port = Integer.parseInt(etConnectPort.getText().toString());
            List list = new ArrayList();
            list.add(new ServerAddrEntity(serverAddress, port));
//            list.add(new ServerAddrEntity("10.19.12.121", 1111));//站点优选
//            list.add(new ServerAddrEntity("10.19.12.121", 1112));//站点优选
            ConnectEntity connectEntity = new ConnectEntity();
            connectEntity.setGmAlgorithm(cbxAlgorithm.isChecked() ? 1 : 0);//是否支持国密
            connectEntity.setServerAddrEntityList(list);//服务器地址列表添加
            if (connectEntity.getGmAlgorithm() == 1) {
                connectEntity.setGmSigCertPath(tvGmSig.getText().toString());//设置国密证书路径
                connectEntity.setGmEncCertPath(tvGmEnc.getText().toString());//设置国密加密证书路径
            }
            connectEntity.setRouteCover(cbxRoutecover.isChecked() ? 1 : 0);//设置是否支持路由覆盖
            connectEntity.setTunnelMold(tunnelType);//设置隧道模式
            connectEntity.setTcpbuffersize(0);//设置tcp缓存区

            List applist = new ArrayList();
            applist.add("com.tencent.mobileqq");
            applist.add("com.leagsoft.emm.vpnsdk");
//            connectEntity.setWhiteApp(applist);//设置白名单
            boolean isStartConnect = VpnUtils.startConnect(this, connectEntity, new OnConnectCallBack() {
                @Override
                public void onConnectSuccess(int authMode) {
                    ToastUtil.show(MainActivity.this, "连接成功");
                    Log.i(TAG, "connect success:" + authMode);
                    if (authMode == ConstValue.LOGIN_USERNAME_AND_PASSWORD) {
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    } else {
                        startActivity(new Intent(MainActivity.this, NameAndCertLoginActivity.class).putExtra("authMode", authMode));
                    }
                }

                @Override
                public void onConnectFail(int code) {
                    if (code == ConstValue.VPN_FORCE_EXIT) {
                        ToastUtil.show(MainActivity.this, "强制下线 响应码:" + code);
                    } else if (code == ConstValue.VPN_RECONNECT_FAIL) {
                        ToastUtil.show(MainActivity.this, "断线重连失败 响应码:" + code);
                    } else if (code == ConstValue.VPN_CONTINUE_FAIL) {
                        ToastUtil.show(MainActivity.this, "dhcp续租失败 响应码:" + code);
                    } else if (code == ConstValue.UDP_TUNNEL_FAIL) {
                        ToastUtil.show(MainActivity.this, "UDP隧道建立失败 响应码:" + code);
                    } else if (code == ConstValue.VPN_NO_INIT) {
                        ToastUtil.show(MainActivity.this, "VPNSDK未进行初始化或者连接参数异常 响应码:" + code);
                    } else {
                        ToastUtil.show(MainActivity.this, "连接失败 响应码:" + code);
                    }
                }
            });

            if (isStartConnect) {
                ToastUtil.show(MainActivity.this, "连接构建成功");
            } else {
                ToastUtil.show(MainActivity.this, "连接构建失败");
            }
        } catch (Throwable throwable) {
            ToastUtil.show(MainActivity.this, "连接异常：" + throwable.toString());
        }
    }

    private void chooseFile(int requestCode) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, requestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && data != null) {
            String filePath = null;
            Uri uri = data.getData();
            if (uri != null) {
                filePath = ContentUriUtil.getPath(this, uri);

                if (requestCode == GM_ENC) {
                    tvGmEnc.setText(filePath);
                } else if (requestCode == GM_SIG) {
                    tvGmSig.setText(filePath);
                }
            }
        }
    }


    public void showSingleAlertDialog() {//0为可靠模式 1为快速模式2为自适应模式
        final String[] items = {"可靠模式", "快速模式", "自适应模式"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
        alertDialog = alertBuilder.create();
        alertBuilder.setTitle("隧道模式选择");
        alertBuilder.setSingleChoiceItems(items, tunnelType, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, items[i], Toast.LENGTH_SHORT).show();
                buTunnelMold.setText("隧道模式：" + items[i]);
                tunnelType = i;
            }
        });
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog.dismiss();
            }
        });
        alertBuilder.show();
    }

}